package com.wxtl.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.wxtl.action.base.BaseAction;
import com.wxtl.util.DateUtil;

public class UploadAction extends BaseAction {
	private final static Log logger = LogFactory.getLog(UploadAction.class);
	
	//属性用来封装上传的文件  
	private File file;
	//ContentType属性用来封装上传文件的类型 
	private String fileContentType;
	//FileName属性用来封装上传文件的文件名 
	private String fileFileName;

	
	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}


	public String upload() throws Exception{
		
		HttpServletRequest request = ServletActionContext.getRequest();
		
		if (file == null || file.getName().equals("")) {
			throw new FileUploadException("请选择上传文件");
		}
		logger.info("Upload file name:" + fileFileName);
	
		InputStream input = null;
		OutputStream output = null;
		String dirStr= ServletActionContext.getServletContext().getRealPath("/upload/upgradepack");
		File dir=new File(dirStr);
		if(!dir.exists())
			dir.mkdirs();
		// 确定服务器端写入文件的文件名
		String outFileName = DateUtil.getDateString(new Date())+fileFileName.substring(fileFileName.lastIndexOf("."));
		String uploadfile = dirStr+"/"+outFileName; 
		
		try{
			//获得上传文件的输入流
			input=new FileInputStream(file);
			//写入服务器的本地文件
			output=new BufferedOutputStream(new FileOutputStream(uploadfile));
			byte[] buffer=new byte[1024];
			int packSize = 0;
			int n;
			while((n=input.read(buffer))!=-1){
				output.write(buffer,0,n);
				packSize += n;
			}	
			//告诉浏览器文件上传成功
			request.setAttribute("filePath", "upgradepack/"+outFileName);
			//记录文件大小
			request.setAttribute("packSize", packSize);
			
			return SUCCESS;
		}catch(Exception e){
			logger.equals(e);
			//throw new FileUploadException("上传文件失败："+e.getMessage());
			return "error";
		}
		finally{
			//必须在finally中关闭输入/输出流
			if(input!=null)
				input.close();
			if(output!=null)
				output.close();
		}
		
	}
}
